<template>
  <div
    class="marquee-container"
    @mouseover="stopAnimation"
    @mouseout="startAnimation"
  >
    <div
      class="marquee-text"
      :style="{ animationDuration: duration + 's', color: color }"
    >
      {{ text }}
    </div>
  </div>
</template>

<script>
export default {
  name: "MarqueeText",
  props: {
    text: {
      type: String,
      default: "默认滚动文字内容",
    },
    speed: {
      type: Number,
      default: 10, // 默认滚动速度，单位为秒
    },
    color: {
      type: String,
      default: "#0ba5ae",
    },
  },
  data() {
    return {
      duration: this.speed, // 动画持续时间
      isMarquee: true, // 是否需要滚动
    };
  },
  methods: {
    // 开始动画
    startAnimation() {
      if (this.isMarquee) {
        const textElement = this.$el.querySelector(".marquee-text");
        textElement.style.animationPlayState = "running";
      }
    },
    // 暂停动画
    stopAnimation() {
      if (this.isMarquee) {
        const textElement = this.$el.querySelector(".marquee-text");
        textElement.style.animationPlayState = "paused";
      }
    },
    // 判断文字是否需要滚动
    checkMarquee() {
      this.$nextTick(() => {
        const container = this.$el.querySelector(".marquee-container");
        const textElement = this.$el.querySelector(".marquee-text");
        if (container && textElement) {
          const containerWidth = container.offsetWidth;
          const textWidth = textElement.offsetWidth;
          this.isMarquee = textWidth > containerWidth;
        }
      });
    },
  },
  watch: {
    // 监听text属性的变化，重新判断是否需要滚动
    text(newVal) {
      this.checkMarquee();
    },
    // 监听speed属性的变化，更新动画持续时间
    speed(newVal) {
      this.duration = newVal;
    },
  },
  mounted() {
    // 组件挂载后判断是否需要滚动
    this.checkMarquee();
  },
};
</script>

<style lang="scss" scoped>
.marquee-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  background-color: #f0f0f0;
  border-radius: 4px;
}

.marquee-text {
  font-size: 18px;
  position: absolute;
  white-space: nowrap;
  animation: marquee linear infinite;
}

@keyframes marquee {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(-100%);
  }
}
</style>
